<template>
    <div class="chat-window">
        <el-card class="left" body-class="left-body">
            <el-button type="primary" size="large" style="width: 100%;" :icon="Plus" plain
                @click="startNewConversation">新建会话</el-button>
            <el-input v-model="input3" style="width: 100%; margin: 10px 0; " size="large" placeholder="Please Input"
                :prefix-icon="Search" @keyup.enter="getRobotconversationListByKeywordsHandle" />
            <ul class="chat-list">
                <li :class="item.id === selectedChatId ? 'chat-list-item select' : 'chat-list-item'"
                    v-for="item in chatList" :key="item.id" @click="selectedChatIdHandle(item.id)">{{ item.name }}</li>
            </ul>
            <!-- <p v-for="o in 4" :key="o" class="text item">{{ 'List item ' + o }}</p> -->
        </el-card>
        <el-card class="right" body-class="right-body">
            <template #header>
                <div class="clearfix">
                    <span>我的聊天室</span>
                </div>
            </template>
            <div class="message-area" ref="messagesContainer">
                <div v-for="(message, index) in messages" :key="index" class="message-item"
                    :class="{ 'my-message': message.sender === '我' }">
                    <div class="message-content">
                        <PreviewMD :content="message.content"></PreviewMD>
                    </div>

                    <!-- <VueMarkdown>{{ message.content }}</VueMarkdown> -->
                    <small class="sender">{{ message.sender }}</small>
                </div>
            </div>
            <div class="message-input">
                <el-input v-model="newMessage" placeholder="请输入消息..." input-style="height: 50px;" @keyup.enter="sendMessage"
                    class="input-with-select" size="large">
                    <template #append>
                        <el-button :icon="Promotion" @click="sendMessage" :loading="isLoading"></el-button>
                    </template>
                </el-input>
            </div>

        </el-card>
    </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import {
    Promotion,
    Plus,
    Search,
} from '@element-plus/icons-vue'
import PreviewMD from '@/components/PreviewMD.vue'
import service from '../service/index'
import type { IRobotconversationDataModal, IAddRobotconversationDataModal, IRobotconversationItemDataModal } from '../type/index'
const { addRobotconversation, getRobotconversationList, addRobotconversationItem, getRobotconversationItemList, getRobotconversationListByKeywords } = service;
import { to } from '../plugin/index'

const newMessage = ref('');
const messages = ref([{ sender: '机器人', content: '您有什么东西都可以在这里提问！' }]);
const isLoading = ref<boolean>(false);
const input3 = ref('');
const chatList = ref<IRobotconversationDataModal[]>([])
const selectedChatId = ref<string>('');

let messagesContainer = ref();

const replaceThinkToBlockquote = (str: string) => {
    return str.replace(/<think>/g, '<blockquote>').replace(/<\/think>/g, '</blockquote>');
}

const getRobotconversationListHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getRobotconversationList());
    loading.close();
    const result = res.data;
    console.log(result);

    if (!err && result.code === 0) {
        chatList.value = result.data;
    } else {
        ElMessage.error('获取账单列表数据失败');
        console.error(err);
    }
}

const getRobotconversationListByKeywordsHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getRobotconversationListByKeywords({ keywords: input3.value }));
    loading.close();
    const result = res.data;
    console.log(result);

    if (!err && result.code === 0) {
        chatList.value = result.data;
    } else {
        ElMessage.error('获取账单列表数据失败');
        console.error(err);
    }
}

const formatMessagesHandle = (list: IRobotconversationItemDataModal[]) => {
    return list.map(item => {
        let sender = '';
        if (item.role === 'assistant') {
            sender = '机器人';
        } else if (item.role === 'user') {
            sender = '我';
        }
        return {
            sender,
            content: replaceThinkToBlockquote(item.content)
        }
    })
}

const getRobotconversationDetailHandle = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const [res, err] = await to(getRobotconversationItemList({
        conversationId: selectedChatId.value
    }));
    loading.close();
    const result = res.data;

    if (!err && result.code === 0) {
        let newData = formatMessagesHandle(result.data);
        messages.value = newData;
        // chatList.value = result.data;
    } else {
        ElMessage.error('获取账单列表数据失败');
        console.error(err);
    }
}

const selectedChatIdHandle = (id: string) => {
    selectedChatId.value = id;
    getRobotconversationDetailHandle();
}

const startNewConversation = () => {
    selectedChatId.value = '';
    messages.value = [{ sender: '机器人', content: '您有什么东西都可以在这里提问！' }];
}

const sendMessage = async () => {
    if (!newMessage.value) {
        return ElMessage({
            message: '输入的内容不能为空',
            type: 'warning',
        })
    }
    isLoading.value = true;
    messages.value.push({
        sender: '我',
        content: newMessage.value
    })
    nextTick(() => {
        // 滚动到messagesContainer的底部
        setTimeout(scrollToBottom, 20)
    });
    // 因为有延迟，所以要替换输入框值，然后清除输入框值
    const msg = newMessage.value;
    newMessage.value = '';
    // 没有 selectedChatId，则代表为初始化，需要新增会话
    if (!selectedChatId.value) {
        // 新增会话及其消息
        const [res, err] = await to(addRobotconversationItem({
            type: 'init',
            msg,
        }));

        const result = res.data;
        if (!err && result.code === 0) {
            console.log(result);
            // 获取会话列表
            await getRobotconversationListHandle();
            console.log(result);
            selectedChatId.value = result.data.conversationId;
            // 新增机器人消息
            messages.value.push({
                sender: '机器人',
                content: replaceThinkToBlockquote(result.data.resMsg)
            });
        } else {
            ElMessage.error('获取失败');
            console.error(err);
        }
    } else {
        // 假若有 selectedChatId，则直接发送消息即可
        const [res, err] = await to(addRobotconversationItem({
            conversationId: selectedChatId.value,
            msg,
        }));
        const result = res.data;
        if (!err && result.code === 0) {
            console.log(result);
            // 新增机器人消息
            messages.value.push({
                sender: '机器人',
                content: replaceThinkToBlockquote(result.data.resMsg)
            });

        } else {
            ElMessage.error('获取失败');
            console.error(err);
        }
    }
    nextTick(() => {
        // 滚动到messagesContainer的底部
        setTimeout(scrollToBottom, 20)
    });
    await getRobotconversationListByKeywordsHandle();
}

const scrollToBottom = () => {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight + 999;
}

onMounted(async () => {
    await getRobotconversationListHandle();
    // initSocket()
    nextTick(() => {
        // 滚动到messagesContainer的底部
        scrollToBottom();
    });
})
</script>
  
<style scoped lang="less">
.chat-window {
    display: flex;
    width: 80%;
    margin: 0 auto;
    // padding: 50px 0;
    padding-bottom: 50px;
    height: 100%;

    .left {
        width: 20%;
        // flex: 1;
        display: flex;
        flex-direction: column;

        ::v-deep .left-body {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100%;

            .chat-list {
                flex: 1;
                list-style: none;
                // padding: 0 10px;
                overflow-y: auto;
                height: 100%;
                padding: 0;

                .chat-list-item {
                    padding: 10px;
                    white-space: nowrap;
                    /* 防止文本换行 */
                    overflow: hidden;
                    /* 超出容器的部分隐藏 */
                    text-overflow: ellipsis;
                    /* 超出部分显示为省略号 */
                    width: 100%;
                    /* 必须设置宽度或最大宽度，以便确定何时开始省略 */
                    display: block;
                    /* 确保元素是块级元素，可以设置宽度 */
                    cursor: pointer;
                    border-radius: 5px;

                    &:hover {
                        background-color: #818b9826;
                    }
                }

                .select {
                    background-color: #818b9826;
                }
            }
        }

    }

    .right {
        flex: 1;
        display: flex;
        flex-direction: column;

        ::v-deep .right-body {
            flex: 1;
            height: 100%;
            background-color: #F6F7FB;

            .message-area {
                height: 85%;
                overflow-y: auto;
                padding: 10px;
                border-bottom: 1px solid #EBEEF5;

                ::v-deep ol {
                    padding-left: 30px;
                }

                ::v-deep ul {
                    padding-left: 30px;
                }
            }

            .message-input {
                height: 15%;
                display: flex;
                align-items: center;
            }

        }
    }

}



.message-item {
    margin-bottom: 15px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.my-message {
    align-items: flex-end;
}

.message-content {
    background-color: #FFFFFF;
    border-radius: 10px;
    padding: 8px 12px;
    /* max-width: 70%; */
    word-wrap: break-word;
}

.my-message .message-content {
    background-color: #409EFF;
    color: white;
}

.sender {
    margin-top: 5px;
    color: #909399;
}
</style>